#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import MySQLdb as mdb
import logging

import time

import mojo_qq

logging.basicConfig(level=20, format='%(asctime)s [%(module)s] %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')



class Announce:
    def __init__(self, db_host, db_user_name, db_password, db_name):
        self._con = mdb.connect(db_host, db_user_name, db_password, db_name, charset='utf8', init_command='SET NAMES UTF8')
        self._con.autocommit(True)
        logging.info("[Order] - DB Init!")

        cur = self._con.cursor()
        cur.execute("SELECT VERSION()")
        ver = cur.fetchone()
        logging.info("[Order] - Database version : %s " % ver)

    def find_all_announce(self, order='DESC'):
        cur = self._con.cursor()
        cur.execute("SELECT * FROM sync_announce t ORDER BY t.`id` %s" % order)

        rows = cur.fetchall()
        return rows

    def find_newest_announce(self):
        cur = self._con.cursor()
        cur.execute("SELECT * FROM sync_announce t WHERE t.synced = 0 ORDER BY t.`id`  DESC LIMIT 1 ")
        return cur.fetchone()

    def set_synced(self, id):
        cur = self._con.cursor()
        cur.execute('update sync_announce t set t.synced = 1 where t.id = %u' % id)

    def close(self):
        self._con.close()

if __name__ == '__main__':
    announce = Announce("180.97.187.89", "test", "1z2x3c4v", "auth")
    qq = mojo_qq.MoJoQQ(mojo_host='180.97.187.89', mojo_port='5000')

    while True:
        row = announce.find_newest_announce()
        if row:
            logging.info("New Announce %s" % row[1])
            qq.send_group_msg('657768313', row[1])
            announce.set_synced(row[0])
        time.sleep(1)

    announce.close()
